const util = require('../../utils/util.js');

const music = wx.createInnerAudioContext({
  useWebAudioImplement: false // 使用微信小程序内置的音频实现
});
music.src = 'http://music.163.com/song/media/outer/url?id=1384026889.mp3';

Page({
  data: {
    Rank: [],
    showOverlay: false,
    animationPaused: false, // 是否暂停动画的标志
  },

  onLoad() {
    music.play(); // 页面加载时播放音乐
  },

  // 获取除本用户之外的其他用户信息
  Rankings() {
    util.request(getApp().globalData.requestUrl + 'users/GetOtherUser', 'GET')
      .then(res => {
        const otherUsers = res.data;
        let requests = otherUsers.map(user => {
          return util.request(getApp().globalData.requestUrl + 'garden/GetFlowerQuantityAndRecordIDs', 'GET', {
              UID: user.UID
            })
            .then(res => {
              const flowerData = res.data.flowerCount;
              let userData = {
                UID: user.UID,
                NickName: user.NickName,
                ProfilePicture: user.ProfilePicture,
                Lv: user.Lv,
                flowerCount: flowerData
              };
              return userData;
            })
            .catch(err => {
              console.error(`获取用户 ${user.UID} 的花朵数量失败:`, err);
              throw err;
            });
        });

        return Promise.all(requests);
      })
      .then(results => {
        // 对 results 进行排序
        results.sort((a, b) => {
          // 首先按照 Lv（关卡进度）降序排序
          if (a.Lv !== b.Lv) {
            return b.Lv - a.Lv;
          } else {
            // 如果关卡进度相同，按照 flowerCount（花朵数量）降序排序
            return b.flowerCount - a.flowerCount;
          }
        });

        // 更新页面数据
        this.setData({
          Rank: results
        });
      })
      .catch(err => {
        console.error('获取用户信息失败:', err);
      });
  },

  GoToShop: function () {
    music.stop(); 
    wx.redirectTo({
      url: '/pages/shop/shop'
    });
  },
  
  GoToGarden: function () {
    music.stop(); 
    wx.redirectTo({
      url: '/pages/garden/garden',
    })
  },

  GoToGame() {
    music.stop(); 
    this.setData({
      animationPaused: true,
    });
    wx.redirectTo({
      url: '/pages/game/game'
    });
  },

  showOverlay() {
    if (!this.data.showOverlay) {
      this.Rankings();
    }
    this.setData({
      showOverlay: !this.data.showOverlay
    });
  },
});